package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class SimpleRedisLock implements ILock{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String KEY_PREFIX="lock:";
    //THREAD_ID_PREFIX只是来区分集群的。一旦项目启动，每个项目的这个值都固定不变的，但不同项目这个值不同
    private static final String THREAD_ID_PREFIX=UUID.randomUUID().toString(true);
    private static final DefaultRedisScript<Long> UNLOCK_SCRIP;
    static {
        UNLOCK_SCRIP=new DefaultRedisScript<>();
        UNLOCK_SCRIP.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIP.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(String key, long timeoutSec) {
        long threadId = Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + key, THREAD_ID_PREFIX + "-" + threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock(String key) {
        String threadId =THREAD_ID_PREFIX + "-" + Thread.currentThread().getId();
        //lua脚本实现查询比较和删除操作的原子性
        stringRedisTemplate.execute(UNLOCK_SCRIP, Collections.singletonList(KEY_PREFIX + key)
                ,threadId);

//        String s = stringRedisTemplate.opsForValue().get(KEY_PREFIX + key);
//        if(threadId.equals(s)){
//            stringRedisTemplate.delete(KEY_PREFIX + key);
//        }
    }
}
